<?php
namespace frontend\modules\pay\controllers\wechat;

use backend\modules\business\models\BusinessPig;
use common\models\business\BusinessGrowup;
use common\models\farmerhouse\FarmerhouseHouse;
use common\models\shop\ShopGoods;
use common\models\shop\ShopHouseOrder;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderGoods;
use common\models\shop\ShopRaisingOrder;
use EasyWeChat\Payment\Order;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;

/**
 * 支付前的下单
 */
class PayController extends BaseMobileController
{


    /**
     * @return string
     * 商城商品的微信支付
     */
    public function actionIndex($oid)
    {

        $order = \Yii::$app->db->createCommand('select price,ordersn from '.ShopOrder::tableName().' where id=:id')
            ->bindValues([':id'=> $oid])
            ->queryOne();

        $allgoods = (new Query())
            ->select('g.title')
            ->from(ShopOrderGoods::tableName().' as og')
            ->leftJoin(ShopGoods::tableName().' as g','og.goodsid=g.id')
            ->where('og.orderid=:oid',[':oid'=>$oid])
            ->all();


        //微信下单
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => implode('、',ArrayHelper::getColumn($allgoods,'title')),
            'detail'           => implode('、',ArrayHelper::getColumn($allgoods,'title')),
            'out_trade_no'     => $order['ordersn'],
            'total_fee'        => floatval($order['price']*100), // 单位：分
//            'total_fee'        => 1, // 单位：分
            'notify_url'       => \Yii::$app->request->hostInfo.'/pay/wechat/callback/notify-shop-pay', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->user['openid']  //$this->user['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        ];

        $worder = new Order($attributes);
        $result = \Yii::$app->wechat->payment->prepare($worder);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = \Yii::$app->wechat->payment->configForPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
        }else{
            return $this->timealert($result->err_code_des);
        }


        return $this->render('@template/mobile/pay.html',[
            'order' => $order,
            'config' => $config,
            'url' => \Yii::$app->request->hostInfo.'/business/user/pork-order/index'
        ]);
    }


    /**
     * @return string
     * 农家乐的支付
     */
    public function actionHouse($oid)
    {

        $order = (new Query())
            ->select('o.price,o.ordersn,f.name')
            ->from(ShopHouseOrder::tableName().' as o')
            ->leftJoin(FarmerhouseHouse::tableName().' as f','f.id=o.houseid')
            ->where('o.id=:oid',[':oid'=>$oid])
            ->one();

        //微信下单
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => $order['name'],
            'detail'           => $order['name'],
            'out_trade_no'     => $order['ordersn'],
            'total_fee'        => floatval($order['price']*100), // 单位：分
//            'total_fee'        => 1, // 单位：分
            'notify_url'       => \Yii::$app->request->hostInfo.'/pay/wechat/callback/notify-house-pay', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->user['openid']  //$this->user['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        ];

        $worder = new Order($attributes);
        $result = \Yii::$app->wechat->payment->prepare($worder);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = \Yii::$app->wechat->payment->configForPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
        }else{
            return $this->timealert($result->err_code_des);
        }

        return $this->render('@template/mobile/pay.html',[
            'order' => $order,
            'config' => $config,
            'url' => \Yii::$app->request->hostInfo.'/business/user/farmer-house-order/index'
        ]);
    }


    /**
     * @return string
     * 领养下单
     */
    public function actionRasing($oid)
    {
        $order = (new Query())
            ->select('o.price,o.ordersn,o.pigvariety')
            ->from(ShopRaisingOrder::tableName().' as o')
            ->where('o.id=:oid',[':oid'=>$oid])
            ->one();

//
        //微信下单
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => $order['pigvariety'],
            'detail'           => $order['pigvariety'],
            'out_trade_no'     => $order['ordersn'],
            'total_fee'        => floatval($order['price']*100), // 单位：分
//            'total_fee'        => 1, // 单位：分
            'notify_url'       => \Yii::$app->request->hostInfo.'/pay/wechat/callback/notify-rasing-pay', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->user['openid']  //$this->user['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        ];
//
        $worder = new Order($attributes);
        $result = \Yii::$app->wechat->payment->prepare($worder);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = \Yii::$app->wechat->payment->configForPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
        }else{
            return $this->timealert($result->err_code_des,'/business/user/pig-order/index');
        }

        return $this->render('@template/mobile/pay.html',[
            'order' => $order,
            'config' => $config,
            'url' => \Yii::$app->request->hostInfo.'/business/user/pig-order/index'
        ]);

    }





    /**
     * @return string
     * 宰杀支付
     */
    public function actionKill($oid)
    {
        $order = (new Query())
            ->select('p.no,g.ordersn,g.killprice as price')
            ->from(BusinessGrowup::tableName().' as g')
            ->leftJoin(BusinessPig::tableName().' as p','p.id=g.pigid')
            ->where('g.id=:oid',[':oid'=>$oid])
            ->one();
//
        //微信下单
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => '仔猪“'.$order['no'].'”宰杀',
            'detail'           => '牧心编号为“'.$order['no'].'”的仔猪的宰杀费用',
            'out_trade_no'     => $order['ordersn'],
            'total_fee'        => floatval($order['price']*100), // 单位：分
//            'total_fee'        => 1, // 单位：分
            'notify_url'       => \Yii::$app->request->hostInfo.'/pay/wechat/callback/notify-kill-pay', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->user['openid']  //$this->user['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        ];

        $worder = new Order($attributes);
        $result = \Yii::$app->wechat->payment->prepare($worder);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = \Yii::$app->wechat->payment->configForPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
        }else{
            return $this->timealert('下单失败','/business/user/my-pigs?status=4');
        }

        return $this->render('@template/mobile/pay.html',[
            'order' => $order,
            'config' => $config,
            'url' => \Yii::$app->request->hostInfo.'/business/user/my-pigs?status=4'
        ]);

    }










}